package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    //SubjectExcelListener  不能交给spring进行管理，需要自己new 不能注入其他对象
    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //读取excel内容，一行一行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new GuliException(20001, "文件数据为空");
        }
        EduSubject exitOneSubjectData = this.exitOneSubjectData(eduSubjectService, subjectData.getOneSubjectName());
        if (exitOneSubjectData == null) {//没有这一行
            exitOneSubjectData=new EduSubject();
            exitOneSubjectData.setParentId("0");
            exitOneSubjectData.setTitle(subjectData.getOneSubjectName());//一级分类名称
            eduSubjectService.save(exitOneSubjectData);
        }
        String parentId = exitOneSubjectData.getId();

        EduSubject exitTwoSubjectData = this.exitTwoSubjectData(eduSubjectService, subjectData.getTwoSubjectName(), parentId);
        if (exitTwoSubjectData == null) {//没有这一行
            exitTwoSubjectData=new EduSubject();
            exitTwoSubjectData.setParentId(parentId);
            exitTwoSubjectData.setTitle(subjectData.getTwoSubjectName());//一级分类名称
            eduSubjectService.save(exitTwoSubjectData);
        }

    }

    //判断一级是否存在
    private EduSubject exitOneSubjectData(EduSubjectService eduSubjectService, String title) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", "0");
        EduSubject one = eduSubjectService.getOne(queryWrapper);
        return one;
    }
    //判断二级是否存在
    private EduSubject exitTwoSubjectData(EduSubjectService eduSubjectService, String title,String pid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", pid);
        EduSubject twoSubject = eduSubjectService.getOne(queryWrapper);
        return twoSubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
